package com.pet.system.interceptor;


import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.RequestUtils;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.pet.framework.constant.ATTFrameWork;
import com.pet.framework.util.FrameCache;
import com.pet.framework.util.StringUtil;
import com.pet.role.util.Logger;
import com.pet.server.po.AuthInfo;
import com.pet.server.po.SysUser;
import com.pet.system.util.SessionHelper;

/**
 * @功能描述:用户操作权限判断
 * author：luo
 * date：Apr 8, 2011 11:42:55 AM 
 */
public class SimpleInterceptor extends AbstractInterceptor {
    private static final Logger logger = Logger.getLogger(SimpleInterceptor.class);
    private static final String AUTH_ERROR="auth_error";
	@Override
	public String intercept(ActionInvocation invocation) {
		//logger.logInfo("intercept.....................");
		String result = null;
		ActionSupport actionSupport = (ActionSupport)invocation.getAction();
		Integer roleId=SessionHelper.getRoleId();
		//SysUser user = SessionHelper.getSysUser();
		
		if(roleId==null){
			actionSupport.addActionError("您还没有登陆或者操作已经过时,请登陆！");
			return AUTH_ERROR;
		}else{
			String uri = getUri(SessionHelper.getRequest());
			List<AuthInfo> list =  FrameCache.getInstance().getAuthInfoCacheByRole(roleId);
			if(list!=null){
				AuthInfo currentAuth = findMenuAuthInfo(uri, list);
				if(currentAuth==null){
					logger.logDebug("auth error");
					actionSupport.addActionError("您没有权限进行此项操作，请与管理员联系!");
					return AUTH_ERROR;
				}else{
					try {
						result = invocation.invoke();
					} catch (Exception e) {
						e.printStackTrace();
						logger.logInfo(e.getMessage());
					}
				}
			}else{
				actionSupport.addActionError("您没有权限进行此项操作，请与管理员联系!");
				return AUTH_ERROR;
			}
		}
		return result;
	}

	private String getUri(HttpServletRequest request) {
		String uri = (String) request.getAttribute("javax.servlet.include.servlet_path");
		if (uri != null) {
			return uri;
		}
		uri = RequestUtils.getServletPath(request);
		if (uri != null && !"".equals(uri)) {
			return uri;
		} else {
			uri = request.getRequestURI();
			return uri.substring(request.getContextPath().length());
		}
	}

	private AuthInfo findMenuAuthInfo(String uri,List<AuthInfo> list){
		AuthInfo currentAuth = null;
		for(AuthInfo mai:list){
			if(authEquals(uri, mai)){
				return mai;
			}
		}
		return currentAuth;
	}
	private boolean authEquals(String uri,AuthInfo mai){
		uri = StringUtil.trim(uri);
		String authRegular = StringUtil.trim(mai.getAuthRegexp());
		return StringUtil.equals(mai.getModel(), ATTFrameWork.LOGIC_TRUE)?StringUtil.regex(authRegular, uri):StringUtil.equals(uri,authRegular);
	}


}
